package com.shanghaionstar.smart;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.MyPost;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.map.common.LocationType;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.weight.ProgressLayout;
import com.shanghaionstar.R;
import com.shanghaionstar.nav.model.MapChoosePoiType;
import com.shanghaionstar.nav.model.SetAddressResult;
import com.shanghaionstar.nav.service.AbstractMapActivity;
import com.shanghaionstar.smart.iview.ISmartHomeView;
import com.shanghaionstar.smart.presenter.SmartHomePresenter;
import com.shanghaionstar.utils.MapHandler;

/**
 * Created by Rengui Lu on 2016/6/12.
 */
@ContentView(R.layout.fragment_container)
public class SmartHomeActivity extends AbstractMapActivity implements ISmartHomeView {
    private static final String TAG = SmartHomeActivity.class.getSimpleName();
    public static final int REQUEST_CODE = 0x100;
    private LinearLayout mContainer;
    //包内可见，共享数据
    public String distance = "500m";
    public String mAccessToken;

    ProgressLayout mScanPl;
    public boolean hasFailed = false;

    private SmartHomePresenter presenter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContainer = (LinearLayout) findViewById(R.id.fragment_container);
        presenter = new SmartHomePresenter(getScheduler());
        presenter.setView(this);
        presenter.switchToHomeApplianceFrg();

//        presenter.checkDeviceList();
    }

    @Override
    public BasePresenter getPresenter() {
        return presenter;
    }

    /**
     * 根据是否存在设备列表显示相关fragment
     //     */
//    private void checkDeviceList(){
//        showProgress(mContainer);
//        SmartRequestUtil.getInstance().getSmartDevices(new ResponseHandler() {
//            @Override
//            public void onSuccess(String tag, String json) {
//                dismissPorgressOnUi(mContainer);
//                processJson(json);
//            }
//            @Override
//            public void onError(String tag, HttpException e) {
//                dismissPorgressOnUi(mContainer);
//                switchToDeviceList();
////                switchToHomeApplianceFrg();
//            }
//        },SmartHomeActivity.this);
//    }

//    /**
//     * @param json
//     * 处理后台返回的Json串
//     */
//    private void processJson(String json) {
//        if(json == null) {
//            switchToHomeApplianceFrg();
//            return;
//        }
//        mSmartDevicesRes = new Gson().fromJson(json,SmartDevicesResponse.class);
//         List<GetSmartDeviceResponse> mSmartDevices = mSmartDevicesRes.devices;
//        if(mSmartDevices != null && !mSmartDevices.isEmpty()) {
//            switchToDeviceList();
//        }else{
//            switchToHomeApplianceFrg();
//        }
//    }

    /**
     * @param mContainer 动态显示进度条
     */
    private void showProgress(LinearLayout mContainer) {
        mScanPl = new ProgressLayout(this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mContainer.addView(mScanPl, lp);
        mScanPl.setVisibility(View.VISIBLE);
    }

    /**
     * @param mContainer 动态隐藏进度条
     */
    private void dismissProgress(LinearLayout mContainer) {
        if (mScanPl == null)
            return;
        mScanPl.setVisibility(View.GONE);
        mContainer.removeAllViews();
    }

    /**
     * @param mContainer 在子线程中要隐藏进度条
     */
    private void dismissPorgressOnUi(final LinearLayout mContainer) {
        new MyPost().post(new Runnable() {
            @Override
            public void run() {
                dismissProgress(mContainer);
            }
        });
    }

//    /**
//     * @param thirdUid
//     * 根据第三方用户名获取token
//     */
//    private void getToken(String thirdUid) {
//        showProgress(mContainer);
//        MSmartSDK.getInstance().getThirdManager().requestToken(thirdUid, new MSmartMapListener() {
//            @Override
//            public void onComplete(Map<String, Object> result) {
//                mAccessToken = (String) result.get(Code.USER_ACCESS_TOKEN);
//                dismissProgress(mContainer);
//                checkDeviceList();
//            }
//
//            @Override
//            public void onError(int errorCode, String errorMsg) {
//                dismissProgress(mContainer);
//                Looper.prepare();
//                showFailureDialog(getString(R.string.smart_get_token_failed));
//                Looper.loop();
//            }
//        });
//    }

//    /**
//     * 显示失败的Dialog提示
//     */
//    private void showFailureDialog(String message) {
//        AlertDialog.Builder alertDialog = new AlertDialog.Builder(SmartHomeActivity.this);
//        alertDialog.create().getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//        alertDialog.setMessage(message);
//        alertDialog.setPositiveButton(R.string.submit, new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                SmartHomeActivity.this.finish();
//            }
//        });
//        alertDialog.show();
//    }
//


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                presenter.onActivityResult(data);
            }
        } else if (requestCode == 1) {
//           data.getExtra("result",poiItemInfo);
            if (data == null)
                return;
            if(resultCode == 1) {
                Object obj = data.getSerializableExtra("result");
                if(obj instanceof SetAddressResult) {
                    SetAddressResult setAddressResult = (SetAddressResult)obj;
                    if(setAddressResult.mapChoosePoiType == MapChoosePoiType.SMART) {
                        PoiItemInfo itemInfo = setAddressResult.poiItemInfo;
                        Fragment mFragment = getCurrentFragment(getSupportFragmentManager());
                        if (mFragment instanceof SmartTriggerFrg) {
                            ((SmartTriggerFrg) mFragment).setHomeAddr(itemInfo);
                        }
                    }
                }
            }
        }
    }


    /*
     * (non-Javadoc)
	 * @see android.support.v4.app.FragmentActivity#onBackPressed() 返回监听
	 */
    @Override
    public void onBackPressed() {
        if (getCurrentFragmentTag().equalsIgnoreCase(SmartDeviceListFrg.class.getSimpleName())) {
            this.finish();
            return;
        }
        int N = getSupportFragmentManager().getBackStackEntryCount();
        if (N == 1) {
            this.finish();
        } else {
            try {
                super.onBackPressed();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void setLoading(boolean isLoading) {
        if (isLoading) {
            showProgress(mContainer);
        } else {
            dismissProgress(mContainer);
        }
    }

    @Override
    public void onResponseError(OnStarException e) {

    }

    @Override
    public void onReponseSuccess(Object object) {

    }

    @Override
    public Activity onActivity() {
        return SmartHomeActivity.this;
    }

    @Override
    public void initMapHandler(MapHandler mapHandler) {
        this.mapHandler = mapHandler;
    }

    @Override
    public void showPoiToMap(PoiItemInfo poiItemInfo, LocationType locationType) {

    }
}
